<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

/** @var $block \Magento\Braintree\Block\Creditcard\Management */

echo $block->getLayout()->getMessagesBlock()->getGroupedHtml();
$defaultExpMonth = '';
$defaultExpYear = '';
$countrySpecificCardTypeConfig = $block->getCountrySpecificCardTypeConfig();
$applicableCardTypeConfig = $block->getCcApplicableTypes();
if ($block->isEditMode()) {
    $creditCard = $block->creditCard();
    $billingAddress = $creditCard->billingAddress;
    $maskedNumber = $creditCard->maskedNumber;
    $isCCDefault = $creditCard->isDefault() ? true : false;
    $defaultCardholder = $creditCard->cardholderName;
    $defaultExpDate = $creditCard->expirationDate;
    $defaultCcType = $creditCard->cardType;
    if ($defaultExpDate) {
        list($defaultExpMonth, $defaultExpYear) = explode('/', $defaultExpDate);
    }
    $defaultFirstName = $billingAddress->firstName;
    $defaultLastName = $billingAddress->lastName;
    $defaultCompany = $billingAddress->company;
    $defaultStreetAddress = $billingAddress->streetAddress;
    $defaultExtendedAddress = $billingAddress->extendedAddress;
    $defaultLocality = $billingAddress->locality;
    $defaultRegion = $billingAddress->region;
    $defaultPostalCode = $billingAddress->postalCode;
    $defaultCountryCodeAlpha2 = $billingAddress->countryCodeAlpha2;
    if ($defaultRegion) {
        $defaultRegionId = $block->getRegionIdByName($defaultRegion, $defaultCountryCodeAlpha2);
    } else {
        $defaultRegionId = '';
    }
} else {
    $isCCDefault = false;
    $defaultCcType = '';
    $defaultCardholder = $block->currentCustomerName().' '.$block->currentCustomerLastName();
    $defaultFirstName = $block->currentCustomerName();
    $defaultLastName = $block->currentCustomerLastName();
    $defaultCompany = '';
    $defaultStreetAddress = '';
    $defaultExtendedAddress = '';
    $defaultLocality = '';
    $defaultRegion = '';
    $defaultRegionId = '';
    $defaultPostalCode = '';
    $defaultCountryCodeAlpha2 = '';
}
$streetValidationClass = $this->helper('Magento\Customer\Helper\Address')->getAttributeValidationClass('street');
$default = $defaultCountryCodeAlpha2;

$clientToken = $block->getClientToken();
$formData = [
    "clientToken" => $clientToken,
    'ajaxSaveUrl' => $block->escapeUrl($block->getAjaxSaveUrl()),
    'isEditMode' => $block->isEditMode() ? true : false,
    'cardToken' => $block->isEditMode() ? $block->escapeHtml($creditCard->token) : '',
    'backUrl' => $block->escapeUrl($block->getBackUrl()),
    'hasVerification' => $block->hasVerification(),
    "countrySpecificCardTypes" => $countrySpecificCardTypeConfig,
    "applicableCardTypes" => $applicableCardTypeConfig,
    "cardTypes" => $block->getCcAvailableTypes(),
    "isFraudDetectionEnabled" => $block->isFraudDetectionEnabled()
];
$serializedFormData = $this->helper('Magento\Framework\Json\Helper\Data')->jsonEncode($formData);
?>
<form
    class="form form-edit-credit-card"  action="<?php echo $block->escapeUrl($block->getFormAction()); ?>"
    method="post" id="form-validate" data-mage-init='{"validation":{}}'>
    <?php echo $block->getBlockHtml('formkey'); ?>
    <fieldset class="fieldset info" data-hasrequired="<?php echo $block->escapeHtml(__('* Required Fields')); ?>">
        <legend class="legend">
            <span><?php echo $block->escapeHtml(__('Credit Card')); ?></span>
        </legend>
        <br>

        <div class="field name required">
            <label for="credit_card_cardholder_name" class="label">
                <span><?php echo $block->escapeHtml(__('Cardholder Name')); ?></span>
            </label>

            <div class="control">
                <input
                    type="text"
                    class="input-text required-entry"
                    id="credit_card_cardholder_name"
                    value="<?php echo $block->escapeHtml($defaultCardholder); ?>"
                    data-validate="{required:true}">
            </div>
        </div>
        <div class="field required type">
            <label for="credit_card_type" class="label">
                <span><?php echo $block->escapeHtml(__('Credit Card Type')); ?></span>
            </label>

            <div class="control">
                <select name="credit_card_type" id="credit_card_type" data-container="credit_card_type"
                        data-validate='{required:true, "validate-cc-type-select":"#credit_card_number"}'>
                    <option value=""><?php echo $block->escapeHtml(__('--Please Select--')); ?></option>
                    <?php foreach ($block->getCcAvailableTypes() as $typeCode => $typeName): ?>
                        <option value="<?php echo $block->escapeHtml($typeCode); ?>"
                            <?php if (stripos($typeName, $defaultCcType) !== false): ?> selected="selected"<?php endif; ?>>
                            <?php echo $block->escapeHtml($typeName); ?>
                        </option>
                    <?php endforeach;
                    ?>
                </select>
            </div>
        </div>
        <div class="field name required">
            <label for="credit_card_number" class="label">
                <span><?php echo $block->escapeHtml(__('Credit Card Number')); ?></span>
            </label>

            <div class="control">
                <input name="credit_card_number"
                       data-container="credit_card_number"
                       type="text"
                       class="input-text required-entry validate-cc-number"
                       id="credit_card_number"
                       autocomplete="off"
                    <?php if ($block->isEditMode()): ?> placeholder="<?php echo $block->escapeHtml($maskedNumber); ?>"<?php endif; ?>
                       data-validate="{'required-number':true, 'validate-cc-number':'#credit_card_number', 'validate-cc-type':'#credit_card_type'}">
            </div>
        </div>
        <div class="field sp-methods required">
            <label for="credit_card_expiration_date" class="label">
                <span><?php echo $block->escapeHtml(__('Expiration Date')); ?></span>
            </label>

            <div class="control">

                <div class="fields group group-2">
                    <div class="field no-label month">
                        <div class="control">
                            <select
                                name="credit_card_expiration"
                                id="credit_card_expiration"
                                class="month validate-cc-exp required-entry"
                                data-validate="{'required-number':true, 'validate-cc-exp':'#credit_card_expiration_yr'}">
                                <?php foreach ($block->getCcMonths() as $k => $v): ?>
                                    <option value="<?php /* @noEscape */ echo $k ? $block->escapeHtml($k) : '' ?>"
                                        <?php if ($k == $defaultExpMonth): ?> selected="selected"<?php endif; ?>>
                                        <?php echo $block->escapeHtml($v); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>


                    <div class="field no-label year">
                        <div class="control">
                            <select
                                name="credit_card_expiration_yr"
                                id="credit_card_expiration_yr"
                                class="year required-entry"
                                data-validate="{required:true}">
                                <?php foreach ($block->getCcYears() as $k => $v): ?>
                                    <option value="<?php /* @noEscape */ echo $k ? $block->escapeHtml($k) : ''; ?>"
                                        <?php if ($k == $defaultExpYear): ?> selected="selected"<?php endif; ?>>
                                        <?php echo $block->escapeHtml($v); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>

            </div>
        </div>
        <?php if ($block->hasVerification()): ?>
        <div class="field sp-methods required">
            <label for="credit_card_cvv" class="label">
                <span><?php echo $block->escapeHtml(__('CVV')); ?></span>
            </label>

            <div class="control">
                <input
                    type="text"
                    title="<?php echo $block->escapeHtml(__('Card Verification Number')); ?>"
                    class="input-text cvv required-entry validate-cc-cvn validate-cc-cvn-autodetect"
                    name="credit_card_cvv"
                    data-container="credit_card_cvv"
                    id="credit_card_cvv"
                    value=""
                    autocomplete="off"
                    data-validate="{'required-number':true, 'validate-cc-cvn':'#credit_card_type'}">
                <?php $content = '<img src=\"' . $block->escapeUrl($block->getViewFileUrl('Magento_Checkout::cvv.png')) .
                    '\" alt=\"' . $block->escapeHtml(__('Card Verification Number Visual Reference')) . '\" title=\"' .
                    $block->escapeHtml(__('Card Verification Number Visual Reference')) . '\" />'; ?>
                <div class="note">
                    <a href="#" id="credit_card-cvv-what-is-this" class="action cvv"
                       title="<?php echo $block->escapeHtml(__('What is this?')); ?>"
                       data-mage-init='{"tooltip": {"content": "<?php /* @noEscape */ echo $content; ?>"}}'>
                        <span><?php echo $block->escapeHtml(__('What is this?')); ?></span>
                    </a>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <div class="field">
            <label class="label">
                <span></span>
            </label>

            <div class="control">
                <input type="checkbox" name="credit_card[options][make_default]" id="credit_card_options_make_default"
                       value="1" <?php /* @noEscape */ echo $isCCDefault ? "checked" : "" ?>>
                <label for="credit_card_options_make_default" class="label">
                    <span><?php echo $block->escapeHtml(__('Make Default')); ?></span>
                </label>
            </div>
        </div>
    </fieldset>
    <fieldset class="fieldset info">
        <legend class="legend">
            <span><?php echo $block->escapeHtml(__('Billing Address')); ?></span>
        </legend>
        <div class="field name billing_address_first_name required">
            <label for="billing_address_first_name" class="label">
                <span><?php echo $block->escapeHtml(__('First Name')); ?></span>
            </label>

            <div class="control">
                <input type="text" class="input-text required-entry " name="credit_card[billing_address][first_name]"
                       id="billing_address_first_name"
                       value="<?php echo $block->escapeHtml($defaultFirstName); ?>"
                       data-validate="{required:true}">
            </div>
        </div>
        <div class="field name billing_address_last_name required">
            <label for="billing_address_last_name" class="label">
                <span><?php echo $block->escapeHtml(__('Last Name')); ?></span>
            </label>

            <div class="control">
                <input type="text" class="input-text required-entry " name="credit_card[billing_address][last_name]"
                       id="billing_address_last_name"
                       value="<?php echo $block->escapeHtml($defaultLastName); ?>"
                       data-validate="{required:true}">
            </div>
        </div>
        <div class="field name billing_address_company">
            <label for="billing_address_company" class="label">
                <span><?php echo $block->escapeHtml(__('Company')); ?></span>
            </label>

            <div class="control">
                <input type="text" class="input-text " name="credit_card[billing_address][company]"
                       id="billing_address_company"
                       value="<?php echo $block->escapeHtml($defaultCompany); ?>">
            </div>
        </div>
        <div class="field name billing_address_street_address required">
            <label for="billing_address_street_address" class="label">
                <span><?php echo $block->escapeHtml(__('Address')); ?></span>
            </label>

            <div class="control">
                <input type="text" class="input-text required-entry "
                       name="credit_card[billing_address][street_address]" id="billing_address_street_address"
                       value="<?php echo $block->escapeHtml($defaultStreetAddress); ?>"
                       data-validate="{required:true}">
            </div>
        </div>
        <div class="field name billing_address_extended_address">
            <label for="billing_address_extended_address" class="label">
                <span></span>
            </label>

            <div class="control">
                <input type="text" class="input-text " name="credit_card[billing_address][extended_address]"
                       id="billing_address_extended_address"
                       value="<?php echo $block->escapeHtml($defaultExtendedAddress); ?>">
            </div>
        </div>
        <div class="field name billing_address_locality required">
            <label for="billing_address_locality" class="label">
                <span><?php echo $block->escapeHtml(__('City')); ?></span>
            </label>

            <div class="control">
                <input type="text" class="input-text required-entry " name="credit_card[billing_address][locality]"
                       id="billing_address_locality"
                       value="<?php echo $block->escapeHtml($defaultLocality); ?>"
                       data-validate="{required:true}">
            </div>
        </div>
        <div class="field region billing_address_region required">
            <label for="billing_address_region" class="label">
                <span><?php echo $block->escapeHtml(__('State/Province')); ?></span>
            </label>

            <div class="control">
                <select id="billing_address_region_id" name="credit_card[billing_address][region_id]"
                        title="<?php echo $block->escapeHtml(__('State/Province')); ?>" class="validate-select" style="display:none;"
                        data-validate="{'validate-select':true}">
                    <option value=""><?php echo $block->escapeHtml(__('Please select region, state or province')); ?></option>
                </select>
                <input type="text" class="input-text " name="credit_card[billing_address][region]"
                       id="billing_address_region"
                       value="<?php echo $block->escapeHtml($block->getPostParam('customer.creditCard.billingAddress.region', $defaultRegion)); ?>">
            </div>
        </div>
        <div class="field zip billing_address_postal_code required">
            <label for="billing_address_postal_code" class="label">
                <span><?php echo $block->escapeHtml(__('Zip/Postal Code')); ?></span>
            </label>
            <div class="control">
                <input type="text" class="input-text required-entry validate-zip-international "
                       name="credit_card[billing_address][postal_code]" id="billing_address_postal_code"
                       value="<?php echo $block->escapeHtml($defaultPostalCode); ?>"
                       data-validate="{required:true, 'validate-zip-international':true}">
            </div>
        </div>
        <div class="field name billing_address_country required">
            <label for="billing_address_country" class="label">
                <span><?php echo $block->escapeHtml(__('Country')); ?></span>
            </label>

            <div class="control">
                <?php /* @noEscape */ echo $block->countrySelect('credit_card[billing_address][country_code_alpha2]', 'billing_address_country', $default); ?>
            </div>
        </div>
    </fieldset>
    <div class="actions-toolbar">
        <div class="primary">
            <button type="submit" id="opc-submit" data-role="opc-submit" class="action save primary"
                    title="<?php echo $block->escapeHtml(__('Submit')); ?>">
                <span><?php echo $block->escapeHtml(__('Submit')); ?></span>
            </button>
        </div>
        <div class="secondary">
            <a class="action back" href="<?php echo $block->escapeUrl($block->getBackUrl()); ?>">
                <span><span><small>&laquo; </small><?php echo $block->escapeUrl(__('Back')); ?></span>
            </a>
        </div>
    </div>
</form>

<script type="text/x-magento-init">
    {
        "#form-validate": {
            "validation": {},
             "braintreeEditForm": <?php /* @noEscape */ echo $serializedFormData; ?>
        },
        "#billing_address_country": {
            "regionUpdater": {
                "optionalRegionAllowed": true ,
                "regionListId": "#billing_address_region_id",
                "regionInputId": "#billing_address_region",
                "postcodeId": "#billing_address_region",
                "form": "#form-validate",
                "regionJson": <?php /* @noEscape */ echo $this->helper('Magento\Directory\Helper\Data')->getRegionJson(); ?>,
                "defaultRegion": "<?php echo $block->escapeHtml($defaultRegionId); ?>",
                "countriesWithOptionalZip":
                <?php /* @noEscape */ echo $this->helper('Magento\Directory\Helper\Data')->getCountriesWithOptionalZip(true); ?>
            }
        }
    }
</script>
